package com.kk.base.service.admin;

import com.kk.base.bean.PageBean;
import com.kk.base.dao.admin.AgingQueryDao;
import com.kk.base.entity.admin.AgingQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class AgingQueryService {

    @Autowired
    private AgingQueryDao agingQueryDao;

    /**
     * 根据始发地模糊分页查询
     * @param pageBean
     * @param agingQuery
     * @return
     */
    public PageBean<AgingQuery> findAllByToAndFromSite(PageBean<AgingQuery> pageBean,AgingQuery agingQuery){
        ExampleMatcher withMatcher = ExampleMatcher.matching().withMatcher("origin", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<AgingQuery> example = Example.of(agingQuery, withMatcher);
        PageRequest pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize());
        Page<AgingQuery> findAll = agingQueryDao.findAll(example,pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }


    public List<AgingQuery> findAllByOriginAndDestination(AgingQuery agingQuery){
        Specification<AgingQuery> specification = (Specification<AgingQuery>) (root,cq,cb)->{
            ArrayList<Predicate> predicates = new ArrayList<Predicate>();

            predicates.add(cb.equal(root.get("origin"),agingQuery.getOrigin()));
            predicates.add(cb.equal(root.get("destination"),agingQuery.getDestination()));

            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };

        return agingQueryDao.findAll(specification);
    }


    /**
     * 保存/编辑
     * @param agingQuery
     * @return
     */
    public AgingQuery save(AgingQuery agingQuery){
        return agingQueryDao.save(agingQuery);
    }

    /**
     * 根据id删除
     * @param id
     */
    public void delById(Long id){
        agingQueryDao.deleteById(id);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public AgingQuery find(Long id){
        return agingQueryDao.find(id);
    }


    /**
     * 判断地点是否存在
     * @param origin
     * @param destination
     * @return
     */
    public boolean isExistOriginAndDestination(String origin,String destination){
        AgingQuery byToAndFromSite = agingQueryDao.findByOriginAndDestination(origin,destination);
        if(byToAndFromSite != null){
                return true;
        }
        return false;
    }

}
